/*
 * @lc app=leetcode.cn id=59 lang=swift
 *
 * [59] 螺旋矩阵 II
 */

// @lc code=start
class Solution {
    func generateMatrix(_ n: Int) -> [[Int]] {
        var result = Array(repeating: Array(repeating: 0, count: n), count: n)
        var top = 0, left = 0, bottom = n - 1, right = n - 1
        var number = 0

        while left <= right && top <= bottom {
            for j in left ... right {
                number += 1
                result[top][j] = number
            }
            if top + 1 <= bottom {
                for i in top + 1 ... bottom {
                    number += 1
                    result[i][right] = number
                }
            }
            if left <= right - 1 && top < bottom {
                for j in (left ... right - 1).reversed() {
                    number += 1
                    result[bottom][j] = number
                }
                if top + 1 <= bottom - 1 {
                    for i in (top + 1 ... bottom - 1).reversed() {
                        number += 1
                        result[i][left] = number
                    }
                }
            }

            top += 1
            left += 1
            bottom -= 1
            right -= 1
        }

        return result
    }
}
// @lc code=end

